package 矩阵;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: TTDB
 * @create: 2025/9/15
 */
public class spiralOrder {
    public List<Integer> spiralOrder(int[][] matrix) {
        //螺旋矩阵
        int m = matrix.length;
        int n = matrix[0].length;
        int[] res = new int[m * n];
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = m - 1;
        int index = 0;
        while(left <= right && top <= bottom){
            for(int i = left; i <= right; i++){
                res[index++] = matrix[top][i];
            }//从左往右
            //注意这个--------------------top在bottom上面，所以判定应该是top > bottom
            if(++top > bottom) break;
            for(int i = top; i <= bottom; i++){
                res[index++] = matrix[i][right];
            }//从上往下
            if(--right < left) break;
            for(int i = right; i >= left; i--){
                res[index++] = matrix[bottom][i];
            }//从右往左
            if(--bottom < top) break;
            for(int i = bottom; i >= top; i--){
                res[index++] = matrix[i][left];
            }
            if(++left > right) break;
        }
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < res.length; i++){
            list.add(res[i]);
        }
        return list;
    }
}
